﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Tulde.WindowsPhone.Music.ViewModel;
using Tulde.WindowsPhone.Music;

namespace MP3tunes.LockerPlayer.UserControls
{
    public partial class Credentials : UserControl
    {
        public event EventHandler<CredentialsEventArgs> Saved;
        public Credentials()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            CredentialsEventArgs ex = new CredentialsEventArgs();
            this.progressBar1.IsIndeterminate = true;
            this.saveBtn.IsEnabled = false;
            ex.Creds = new Mp3TunesCredentials
            {
                Password = this.txtPassword.Text,
                UserName = this.txtUserName.Text
            };
            bool? save = this.saveCreds.IsChecked;
            MusicServiceFactory.Instance.Authenticate(ex.Creds, token =>
            {
                this.progressBar1.IsIndeterminate = false;
                if (token.Status != 0)
                {
                    if (save.HasValue && save.Value)
                    {
                        SettingsProvider.Settings.SaveLogonCredentials = save.Value;
           
                        SecurityProvider.SaveCredentials(ex.Creds);
                        SettingsProvider.Save();
                    }
                    SecurityProvider.SetAuthenticationTokens(token);
                    this.saveBtn.IsEnabled = true;
                    if (this.Saved != null)
                    {
                        this.Saved(this, ex);
                    }
                }
                else
                {
                    this.errorMessage.Visibility = System.Windows.Visibility.Visible;
                    this.errorMessage.Text = token.ErrorMessage;
                    this.saveBtn.IsEnabled = true;
                }
             
            });
         

           
        }
    }
    public class CredentialsEventArgs : EventArgs
    {
        public Mp3TunesCredentials Creds { get; set; }
    }
}
